package com.example.coordinartordemo.demo6;

import android.animation.ArgbEvaluator;
import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.example.coordinartordemo.R;

import java.lang.ref.WeakReference;

public class HeaderFloatBehavior  extends CoordinatorLayout.Behavior<View> {

    private WeakReference<View> dependentView;
    private ArgbEvaluator argbEvaluator;

    public HeaderFloatBehavior(Context context, AttributeSet attrs){
        super(context,attrs);
        argbEvaluator = new ArgbEvaluator();
    }

    @Override
    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        if (null != dependency && dependency.getId() == R.id.scrolling_header){
            dependentView = new WeakReference<>(dependency);
            return true;
        }

        return false;
    }

    @Override
    public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        Resources resources = getDependentView().getResources();
        final float progress = 1.f - Math.abs(dependency.getTranslationY()/(dependency.getHeight() - resources.getDimension(R.dimen.collapsed_header_height)));

        float collapsedOffsset = resources.getDimension(R.dimen.collapsed_float_offset_y);
        float initOffset = resources.getDimension(R.dimen.init_float_offset_y);
        float translateY = collapsedOffsset + (initOffset - collapsedOffsset) * progress;
        child.setTranslationY(translateY);

        //background
        child.setBackgroundColor((int)argbEvaluator.evaluate(progress,resources.getColor(R.color.colorCollapsedFloatBackground),
                resources.getColor(R.color.colorInitFloatBackground)));

        // Margins
        final float collapsedMargin = resources.getDimension(R.dimen.collapsed_float_margin);
        final float initMargin = resources.getDimension(R.dimen.init_float_margin);
        final int margin = (int) (collapsedMargin + (initMargin - collapsedMargin) * progress);
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
        lp.setMargins(margin, 0, margin, 0);
        child.setLayoutParams(lp);
        return true;
    }

    private View getDependentView(){
        return dependentView.get();
    }
}
